package com.dms.common.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.dms.common.config.OssConfig;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Component
public class OssUtils {
    private final OSS ossClient;
    private final OssConfig ossConfig;

    public OssUtils(OssConfig ossConfig) {
        this.ossConfig = ossConfig;
        this.ossClient = new OSSClientBuilder().build(
            ossConfig.getEndpoint(),
            ossConfig.getAccessKeyId(),
            ossConfig.getAccessKeySecret()
        );
    }

    public String uploadFile(MultipartFile file, String directory) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = directory + "/" + UUID.randomUUID().toString() + extension;
        
        ossClient.putObject(ossConfig.getBucketName(), fileName, file.getInputStream());
        return ossConfig.getUrlPrefix() + fileName;
    }

    public void deleteFile(String fileUrl) {
        String fileName = fileUrl.replace(ossConfig.getUrlPrefix(), "");
        ossClient.deleteObject(ossConfig.getBucketName(), fileName);
    }
} 